package com.ifuncat.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ifuncat.gulimall.common.to.SkuReductionTo;
import com.ifuncat.gulimall.common.to.SpuBoundTo;
import com.ifuncat.gulimall.common.utils.PageUtils;
import com.ifuncat.gulimall.common.utils.Query;
import com.ifuncat.gulimall.common.utils.R;
import com.ifuncat.gulimall.product.dao.SpuInfoDao;
import com.ifuncat.gulimall.product.entity.*;
import com.ifuncat.gulimall.product.feign.CouponFeignService;
import com.ifuncat.gulimall.product.service.*;
import com.ifuncat.gulimall.product.vo.Attr;
import com.ifuncat.gulimall.product.vo.Images;
import com.ifuncat.gulimall.product.vo.SpuSaveVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

//    @Autowired
//    private WareFeignService wareFeignService;
//
//    @Autowired
//    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品spu信息
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存spu基本信息:pms_spu_info
        Long spuId = saveBaseInfo(vo);
        //2.保存spu的描述图片:pms_spu_info_desc
        saveSpuDesc(vo, spuId);
        //3.保存spu的图片集：pms_spu_images
        spuImagesService.saveImages(spuId, vo.getImages());
        //4.保存spu的规格参数：pms_product_attr_value
        saveSpuAttr(vo, spuId);
        //5.保存spu的积分信息：gulimall_sms--->sms_spu_bounds
        saveBonds(vo, spuId);
        //6.保存当前spu对应的所有sku信息：pms_sku_info
        saveSkuInfo(vo, spuId);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            //如: where 1=1 and (id='' or spu_name like '')
            queryWrapper.and(wrapper -> wrapper.eq("id", key).or().like("spu_name", key));
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    private void saveSkuInfo(SpuSaveVo vo, Long spuId) {
        if (CollectionUtils.isEmpty(vo.getSkus())) return;

        vo.getSkus().forEach(item -> {
            String defaultImg = "";
            for (Images image : item.getImages()) {
                if (image.getDefaultImg() == 1) {
                    defaultImg = image.getImgUrl();
                }
            }

            //sku的基本信息:pms_sku_info
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(item, skuInfoEntity);
            skuInfoEntity.setBrandId(vo.getBrandId());
            skuInfoEntity.setCatalogId(vo.getCatalogId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSpuId(spuId);
            skuInfoEntity.setSkuDefaultImg(defaultImg);
            skuInfoService.save(skuInfoEntity);

            //sku的图片信息：pms_sku_image
            List<SkuImagesEntity> imgEntityList = item.getImages().stream().map(img -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuImagesEntity.setImgUrl(img.getImgUrl());
                        skuImagesEntity.setDefaultImg(img.getDefaultImg());
                        return skuImagesEntity;
                    }).filter(i -> !StringUtils.isEmpty(i.getImgUrl()))
                    .collect(Collectors.toList());
            skuImagesService.saveBatch(imgEntityList);

            //sku的销售属性：pms_sku_sale_attr_value
            List<Attr> attr = item.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());

            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

            //sku的优惠、满减等信息：gulimall_sms--->sms_sku_ladder、sms_sku_full_reduction、sms_member_price
            SkuReductionTo skuReductionTo = new SkuReductionTo();
            BeanUtils.copyProperties(item, skuReductionTo);
            skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
            if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {
                R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                if (r1.getCode() != 0) {
                    log.error("远程保存sku积分信息失败");
                }
            }
        });
    }

    /**
     * 保存spu的积分信息
     */
    private void saveBonds(SpuSaveVo vo, Long spuId) {
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(vo.getBounds(), spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }
    }

    /**
     * 保存spu的规格参数：pms_product_attr_value
     */
    private void saveSpuAttr(SpuSaveVo vo, Long spuId) {
        List<ProductAttrValueEntity> list = vo.getBaseAttrs().stream().map(item -> {
            ProductAttrValueEntity entity = new ProductAttrValueEntity();
            entity.setAttrId(item.getAttrId());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            entity.setAttrName(attrEntity.getAttrName());
            entity.setAttrValue(item.getAttrValues());
            entity.setQuickShow(item.getShowDesc());
            entity.setSpuId(spuId);
            return entity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(list);
    }

    /**
     * 保存spu的描述图片:pms_spu_info_desc
     */
    private void saveSpuDesc(SpuSaveVo vo, Long spuId) {
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", vo.getDecript()));
        spuInfoDescService.save(spuInfoDescEntity);

    }

    /**
     * 保存spu基本信息:pms_spu_info
     */
    private Long saveBaseInfo(SpuSaveVo vo) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.insert(spuInfoEntity);
        return spuInfoEntity.getId();
    }

}